package com.lyloou.practice.service.impl;


import com.lyloou.practice.dao.AccountDao;
import com.lyloou.practice.pojo.Account;
import com.lyloou.practice.service.TransferService;
import com.lyloou.practice.utils.TransactionManager;

/**
 * @author 应癫
 */
public class TransferServiceImpl implements TransferService {

    private AccountDao accountDao;
    TransactionManager transactionManager;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        try {
            transactionManager.beginTransaction();
            Account fromAccount = accountDao.queryAccountByCardNo(fromCardNo);
            Account toAccount = accountDao.queryAccountByCardNo(toCardNo);
            fromAccount.setMoney(fromAccount.getMoney() - money);
            toAccount.setMoney(toAccount.getMoney() + money);
            accountDao.updateAccountByCardNo(fromAccount);
//            int c = 1 / 0;
            accountDao.updateAccountByCardNo(toAccount);
            transactionManager.commit();
        } catch (Exception e) {
            transactionManager.rollback();
            throw e;
        }
    }
}
